package com.ace.user.base;

import com.ace.user.module.mapper.UserUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Lazy;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author weihl
 * @date 2019/10/12 15:38
 */
@Slf4j
@Component
public class MQTTApplicationRunner implements ApplicationRunner {
    @Resource
    private UserUserMapper userMapper;

    @Lazy
    @Resource
    private MqttPahoMessageDrivenChannelAdapter channelAdapter;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("-------------- application runner ------------");
        List<String> appIds = userMapper.selectAllAppId();
        if (appIds == null || appIds.size() == 0) {
            log.info("no active appId");
            return;
        }
        log.info("active group size:" + appIds.size());
        for (String appId : appIds) {
            try {
                channelAdapter.addTopic(appId);
            }catch (Exception e){
                log.warn(e.getMessage());
                continue;
            }
            log.info("Succeed to subscribe topic:" + appId);
        }
        log.info("All done for subscribing active appIds");
    }
}
